package com.foreveross.util;

import java.beans.PropertyDescriptor;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import com.foreveross.vo.HouseUser;
import com.foreveross.vo.OrderInfo;

import jxl.Cell;
import jxl.CellType;
import jxl.DateCell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

/**
 * 
* @ClassName: ExcelUtil 
* @Description: TODO(Excel导入导出类) 
*
 */
public class ExcelUtil<T> {
	//Excel表头
	private  String[] titles = {
			"买家姓名", "商品名", "商铺名", "楼盘名", "原价(元)", 
			"现价(元 )", "购买数量", "账单时间", "支付方式", "支付状态"
	};
	
	private  String[] valueName = {
			
	};

	
	private List<T> list = new ArrayList<T>();
	//导出文件名
	private  String fileName = "订单管理";
	
	
	
	private ExcelUtil(){
		
	}
	
	public ExcelUtil(String fileName,String[] titles,String[] valueName,List<T> list ){
		this.titles = titles;
		this.fileName = fileName;
		this.valueName = valueName;
		this.list = list;
	}

	/**
	 * 
	* @Title: impExcel 
	* @Description: TODO(解析Excel) 
	* @param @param is 要解析的文件
	* @param @param start 从第start列开始解析
	* @param @param end  解析到end列
	* @param @throws Exception    设定文件 
	* @return List<Map<String,String>>    Excel表头和内容映射的集合
	* @throws
	 */
	public static List<Map<String, String>> impExcel(InputStream is, int start, int end) throws Exception {
		List<Map<String, String>> maps = new ArrayList<Map<String, String>>();
		Workbook workbook = Workbook.getWorkbook(is); 
		Sheet sheet = workbook.getSheet(0);
		int rowSize = sheet.getRows(); //行数
        //int colSize = sheet.getColumns(); //列数  
        for (int i = 1; i < rowSize; i++) {
        	System.out.println("第" + i + "行");
        	Map<String, String> map = new HashMap<String, String>();
        	for (int j = start; j <= end; j++) {
            	Cell til = sheet.getCell(j, 0);  //Excel标题
        		Cell con = sheet.getCell(j, i);   //Excel内容
            	String title = til.getContents().trim();
            	String content = "";
            	if (con.getType() == CellType.DATE) {
            		//解析日期类型 jxl会把日期类型自动解析成 yy-MM-dd
            		DateCell datec11 = (DateCell) con;
                    Date date = datec11.getDate();
                    content = DateUtil.DateToString(date,"yyyy-MM-dd HH:mm:ss");
                    		//.parseDateToDate(date);//yyyy-MM-dd
            	} else {
            		content = con.getContents().trim();
            	}
        		System.out.println("title == " + title + ", content = " + content);
        		map.put(title, content);
        	}
        	maps.add(map);
        }
        return maps;
	}
	
	public void expExcel(HttpServletResponse response) throws Exception {
		OutputStream os = null;
		try {
			os = response.getOutputStream();
			WritableWorkbook workbook = Workbook.createWorkbook(os);
			response.setContentType("application/x-rar-compressed");
			response.addHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName+".xls", "utf-8"));
		    WritableSheet sheet = workbook.createSheet(fileName, 0);
		    genHead(sheet);
		    genBody(sheet);
		    workbook.write(); 
		    workbook.close();
		    os.flush();
		} catch (Exception e) {
			throw e;
		} finally {
			if (null != os) {
				os.close();
			}
		}
	}
	
	private  void expExcel(OutputStream os) throws Exception {
		WritableWorkbook workbook = Workbook.createWorkbook(os);
	    WritableSheet sheet = workbook.createSheet(fileName, 0);
	    genHead(sheet);
	    genBody(sheet);
	    workbook.write(); 
	    workbook.close();
	}
	
	private  void genHead(WritableSheet sheet) throws Exception {
		Label label;
		for (int i = 0; i < titles.length; i++) {
			//Label(列号,行号 ,内容 )
			label = new jxl.write.Label(i , 0, titles[i]); //跳过第一列
			sheet.addCell(label); 
		}
	}
	
	private  void genBody(WritableSheet sheet) throws Exception {
		int row  = list.size();//Excel内容行数
		for (int i = 0; i < row; i++) {
			T o = list.get(i);
			Label label = null;
			for (int j = 0; j < titles.length; j++) {
				//Label(列号,行号 ,内容 )
				label = new jxl.write.Label(j, i+1, getContent(j, o));
				sheet.addCell(label); 
			}
		}
	}
	
	private  String getContent(int index, T o) {
		String value = "";
	    if(o instanceof Map){
	    	Map<String,Object> map = (Map<String,Object>)o;
	    	value = String.valueOf(map.get(valueName[index]));
	    }else{
	    	Object obj = invoke(valueName[index], o);
	    	if(obj !=null) value = obj.toString();
	    }
		return value;
	}
	
	private <T> Object invoke(String name,T o){
		try{
			String strName[] = name.split("-");
			Class clazz = o.getClass();
			//读数据
			PropertyDescriptor pd = new PropertyDescriptor(strName[0], clazz);
			//获得写方法
			Method method = pd.getReadMethod();
			Object obj = method.invoke(o);
			
			if(strName.length != 1){
				return invoke(name.substring(strName[0].length()+1), obj);
			}else{
				return obj;
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		return null;
	}
	
	public static void main(String[] args) throws Exception {
		OrderInfo o = new OrderInfo();
		o.setCount(2);
		HouseUser h = new HouseUser();
		h.setAddress("a基本原则");
		o.setHouseUser(h);
		Map<String,Object> map = new HashMap<String, Object>();
		map.put("name", 123123);
		ExcelUtil<Map<String,Object>> e = new ExcelUtil<Map<String,Object>>();
		//Object t = e.invoke("houseUser-address", o);
		System.out.println(e.getContent(0, map));
		
	}
}
